﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KC.DataAccess.Processor;

namespace KC.Business.Processor
{
	public abstract class ProcessorBase : IDisposable
	{
		public Schedule schedule;
		protected ProcessorDataContext dc;

		public ProcessorBase()
		{
			dc = new ProcessorDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["Processor"].ConnectionString);
			var scheds = from s in dc.Schedules where s.Name == GetType().Name select s;
			schedule = scheds.Count() == 0 ? null : scheds.First();
		}

		public abstract bool Run();
		public bool isDue()
		{
			if (schedule == null) return false;
			return schedule.NextRun <= DateTime.Now;
		}

		protected void LogError(Exception ex)
		{
			try {
				dc.Errors.InsertOnSubmit(new Error() { Datetime = DateTime.Now, ExType = ex.GetType().Name, Message = ex.Message, StackTrace = (ex.StackTrace ?? Environment.StackTrace).Replace("at ", "\r\nat ") });
				dc.SubmitChanges(); }
			catch { }
		}
		protected void LogError(string ex)
		{
			try {
				dc.Errors.InsertOnSubmit(new Error() { Datetime = DateTime.Now, ExType = ex.GetType().Name, Message = ex, StackTrace = Environment.StackTrace.Replace("at ", "\r\nat ") });
				dc.SubmitChanges(); } 
			catch { }
		}
		protected void AddDetail(string msg)
		{
			msg = msg.Trim() + "\r\n";
			dc.Details.InsertOnSubmit(new Detail() { datetime = DateTime.Now, text = msg });
			dc.SubmitChanges();
		}
		public void Dispose()
		{
			if (dc != null) dc.Dispose();
			schedule = null;
		}
	}
}
